package cn.ckx.coding.common.utils;

import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * @author gengyang.chen
 * @version 1.0.0
 * @Description:
 *
 * Set交集、差集工具方法
 *
 * @ClassName: SetUtil
 * @date 2020/9/20 10:57 上午
 */
public class SetUtil {

    /**
     * 求两个Set的差集
     * @param sourceSet
     * @param subtractingSet
     * @param <T>
     * @return
     */
    public static <T> Set<T> getDifferenceSet(Set<T> sourceSet, Set<T> subtractingSet) {
        Set<T> result = new HashSet<>(Optional.ofNullable(sourceSet)
                .orElse(Collections.emptySet()));
        result.removeAll(Optional.ofNullable(subtractingSet)
                .orElse(Collections.emptySet()));
        return result;
    }

    /**
     * 求两个Set的交集
     * @param sourceSet
     * @param anotherSet
     * @param <T>
     * @return
     */
    public static  <T> Set<T> getIntersectionSet(Set<T> sourceSet, Set<T> anotherSet) {
        Set<T> result = new HashSet<>(Optional.ofNullable(sourceSet)
                .orElse(Collections.emptySet()));
        result.retainAll(Optional.ofNullable(anotherSet)
                .orElse(Collections.emptySet()));
        return result;
    }

}
